# coding: utf-8

import json
import sys
import traceback
import warnings
import re
import requests

from urllib3.exceptions import InsecureRequestWarning

warnings.filterwarnings("ignore", category=InsecureRequestWarning)


headers = {
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Cursor/0.1.1 Chrome/108.0.5359.62 Electron/22.0.0 Safari/537.36',
    'content-type': 'application/json',
}


def fetch(query):
    json_data = {
        'userRequest': {
            'message': query,
            'currentRootPath': '',
            'currentFileName': '',
            'currentFileContents': '',
            'precedingCode': [],
            'currentSelection': None,
            'suffixCode': [],
            'copilotCodeBlocks': [],
            'customCodeBlocks': [],
            'codeBlockIdentifiers': [],
            'msgType': 'freeform',
            'maxOrigLine': None,
        },
        'userMessages': [],
        'botMessages': [],
        'contextType': 'copilot',
        'rootPath': '',
    }
    response = None
    for i in range(3):
        response = requests.post('https://aicursor.com/conversation', headers=headers, data=json.dumps(json_data),
                                 verify=False, timeout=10)
        if response.status_code == 200:
            response.encoding = response.apparent_encoding
            break
    if response:
        source = response.text.encode("utf-8").decode("unicode_escape").replace("data: ", "")
        # print(source)
        content_list = [i.replace('"', '') for i in source.split("\n")]
        # print(content_list)
        for index, each_item in enumerate(content_list[:]):
            if each_item.isdigit() and index < len(content_list) - 1 and content_list[index + 1] == ".":
                content_list[index] = f"\n{each_item}"
            if each_item in ["。", "："]:
                content_list[index] = f"{each_item}\n"

        for c_index, i in enumerate(content_list[:]):
            if i == "" and c_index < len(content_list) - 2 and content_list[c_index + 1] == "":
                content_list[c_index + 1] = i.replace("", "\n")
            elif i == "" and c_index < len(content_list) - 2 and content_list[c_index + 1] != "":
                content_list[c_index] = i.replace("", "\n")

        beautiful_content = "".join(content_list)
        new_content = re.sub(r"<.*?>|markdown|\[DONE\]", "", beautiful_content + "\n").replace("CursorBot", "Xchen的智能助手")
        new_content =  print(new_content.replace("```", "\n```"))
        print(new_content)
    else:
        print(":warning-emoji: [bold red blink] 查询失败了[/]")


while True:
    try:

        input_query = input("[bolb green]请输入要查询的内容,退出输入 [i]n[/i] 或者 [i]q[/i] :smiley: \n")
        print("[bold red] 以下是回答的内容")
        if input_query.lower() in ["n", "q"]:
            break
        with print("Loading...", spinner="runner"):
            print(input_query)
        print("[bold red] 回答结束")
    except Exception:
        print(traceback.format_exc(), style="danger")
    except KeyboardInterrupt:
        sys.exit()